package com.atguigu.common.validator;


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lvling
 */
public class NotAllBlankValidator implements ConstraintValidator<NotAllBlank, Object> {

    private String[] fields;

    private static final Map<String, Field> fieldCache = new ConcurrentHashMap();

    @Override
    public void initialize(NotAllBlank constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.fields = constraintAnnotation.fields();
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext constraintValidatorContext) {
        if (null == obj) {
            return true;
        }
        for (String field : fields) {
            String value = getFieldValue(field, obj);
            if (value == null) {
                continue;
            }
            value = value.trim();
            if (value.length() > 0) {
                return true;
            }
        }
        return false;
    }

    private String getFieldValue(String fieldName, Object obj) {
        String fieldCacheKey = obj.getClass().getCanonicalName() + "#" + fieldName;
        Field field = fieldCache.get(fieldCacheKey);
        if (field == null) {
            synchronized (obj.getClass()) {
                field = fieldCache.get(fieldCacheKey);
                if (field == null) {
                    field = ValidationUtils.getDeclaredField(obj.getClass(), fieldName);
                    if (field == null) {
                        return null;
                    }
                    fieldCache.put(fieldCacheKey, field);
                }
            }
        }
        try {
            return (String) field.get(obj);
        } catch (IllegalAccessException e) {
            return null;
        }
    }

}
